/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.vtutor.check.object;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ru.miit.elearning.vtutor.check.CheckObjectResult;
import ru.miit.elearning.vtutor.data.CheckObject;
import ru.miit.elearning.vtutor.ftp.FTPClientDecorator;
import ru.miit.elearning.vtutor.wsclient.VlStudent;




/**
 *
 * @author Cyclone
 */
public class CheckObjectDirType extends AbstractCheckObject {

    private static final boolean DEBUG = false, SHOW_RESULT = false;

    CheckObjectDirType(CheckObject co) {
        super(co);
    }

    @Override
    public CheckObjectResult check(VlStudent student, FTPClientDecorator ftp) {
        CheckObjectResult cor = new CheckObjectResult();

        JSONObject jsonCheck = null;


        try {
            jsonCheck = new JSONObject();

            String home = student.getZOSHomeFolder();
            path = path.replace("<userid>", home);
            if (home.indexOf("/") == 0) {
                path = home + "/" + path;
            } else {
                path = "/" + home + "/" + path;
            }

            jsonCheck.put("path", path);
            jsonCheck.put("type", type);

            // checking directory
            boolean directoryFound = ftp.cd(path) && (ftp.list() != null);

            // || ftp.getReplyCode() == 550
            if (!directoryFound) {
                return getNotFoundCheckDetails(cor, jsonCheck);
            }
            // dir found

            if ((content != null) && !(content.length == 0)
                    && !((content.length == 1) && (content[0].equals("null")
                    || content[0].equals("")))) {
                // dir found, need to check content


                String contentString = null;

                String[] ftpFiles = ftp.list();

                if (ftpFiles == null) {
                    contentString = "";
                } else {
                    StringBuffer contentBuffer = new StringBuffer();
                    for (int i = 0; i < ftpFiles.length; i++) {
                        contentBuffer.append(ftpFiles[i] + "\n");
                    }
                    contentString = new String(contentBuffer);
                }

                boolean dirChecked = true;
                jsonCheck.put("status", AbstractCheckObject.STATUS_FOUND_AND_CHECKING);
                JSONArray jsonCombs = new JSONArray();
                for (int i = 0; i < content.length; i++) {
                    JSONObject jsonComb = new JSONObject();
                    content[i] = content[i].replaceAll("<userid>", student.getZOSHomeFolder());
                    jsonComb.put("comb", content[i]);
                    
                    if (content[i].toLowerCase().equals("<notnull>")) {
                        if (contentString.length() > 0) {
                            // fileChecked = true;
                            // --- dirDetails += "\n" + strings.getString("notEmpty");
                            jsonComb.put("check", AbstractCheckObject.COMB_FOUND);
                        } else {
                            dirChecked = false;
                            // --- dirDetails += "\n" + strings.getString("empty");
                            jsonComb.put("check", AbstractCheckObject.COMB_NOT_FOUND);
                            //dirDetails += "\n" + Clock.addSeconds(typeName+" пуст"+(typeInt==0?"":"а")+".");
                        }
                    } else {

                        // TODO Removed REGEXP here
                        //(!contentString.matches(".*" + content[i] + ".*"))
                        // if (contentString.indexOf(content[i]) != -1) {
                        if (contentString.contains(content[i])) {
                            // --- dirDetails += "\n" + strings.getString("combinationFound").replaceAll(":comb", content[i]);
                            jsonComb.put("check", AbstractCheckObject.COMB_FOUND);
                            //dirDetails += "\n" + Clock.addSeconds("Комбинация \"" + content[i] + "\" найдена.");
                        } else {
                            // --- dirDetails += "\n" + strings.getString("combinationNotFound").replaceAll(":comb", content[i]);
                            jsonComb.put("check", AbstractCheckObject.COMB_NOT_FOUND);
                            //dirDetails += "\n" + Clock.addSeconds("Не найдена комбинация \"" + content[i] + "\".");
                            dirChecked = false;
                        }
                    }
                    jsonCombs.put(jsonComb);
                }
                jsonCheck.put("combs", jsonCombs);


                /* // ---
                if (dirChecked) {
                dirDetails += "\n" + strings.getString("checked");
                } else {
                dirDetails += "\n" + strings.getString("notСhecked");
                }
                 */

                jsonCheck.put("result", dirChecked ? AbstractCheckObject.RESULT_CHECK_OK : AbstractCheckObject.RESULT_CHECK_FAILED);

                if (SHOW_RESULT) {
                    System.out.println("\tSHOW_RESULT: Dir \"" + path + "\t " + (dirChecked ? "" : "not ") + " checked");
                }

                cor.setChecked(dirChecked);
                // --- cor.setDetails(dirDetails);
                cor.setDetails(jsonCheck);
                return cor;

            } else {
                // dir found, no need to check content

                // --- dirDetails = Clock.addSeconds(strings.getString("found").replaceAll(":name", path));
                // --- dirDetails += "\n" + strings.getString("checked");

                jsonCheck.put("status", AbstractCheckObject.STATUS_FOUND);
                jsonCheck.put("result", AbstractCheckObject.RESULT_CHECK_OK);

                if (SHOW_RESULT) {
                    System.out.println("\tSHOW_RESULT: Dir \"" + path + "\" found");
                }

                cor.setChecked(true);
                // --- cor.setDetails(dirDetails);
                cor.setDetails(jsonCheck);
                return cor;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TODO What to return in case of Exception during check?
            // --- dirDetails = Clock.addSeconds("Произошла ошибка при проверке: " + e.getMessage());
            // --- dirDetails += "\nФайл не засчитан.";

            try {
                jsonCheck.put("status", AbstractCheckObject.STATUS_EXCEPTION);
                jsonCheck.put("result", AbstractCheckObject.RESULT_CHECK_FAILED);
            } catch (JSONException ex) {
                Logger.getLogger(CheckObjectFileType.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (SHOW_RESULT) {
                System.out.println("\tSHOW_RESULT: File \"" + path + "\" not checked found due to Exception");
            }

            cor.setChecked(false);
            cor.setDetails(jsonCheck);
            return cor;
        }
    }

    @Override
    public String getTextContent(FTPClientDecorator ftp) {
        String textContent = null;
        try {

            String[] list = null;
            boolean directoryFound = ftp.cd(path) && ((list = ftp.list()) != null);

            /*
            // for PDS
            boolean isPDS = false;
            if (!directoryFound && type == CheckObjectTypeHelper.CHECH_OBJECT_TYPE_PDS) {
            String[] qualifiers = path.split("\\.");
            String pdsName = qualifiers[qualifiers.length - 1];

            // ftp.cd(path);
            ftp.cd("..");
            String[] parentDirecotryContent = ftp.list();
            for (int i = 0; i < parentDirecotryContent.length; i++) {
            if (parentDirecotryContent[i].equalsIgnoreCase(pdsName)) {
            directoryFound = true;
            isPDS = true;
            break;
            }
            }
            }
             */

            if (directoryFound) {
                StringBuffer sb = new StringBuffer();
                for (String dir : list) {
                    sb.append(dir + "\n");
                }
                textContent = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return textContent;
    }
}
